package com.example.musicplayer.utils

import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

object HttpUtils {
    private val client = OkHttpClient()

    /**
     * 发送 GET 请求
     * @param url 请求的 URL
     * @param callback 回调接口，处理响应
     */
    @JvmStatic
    operator fun get(url: String?, callback: HttpCallback?) {
        val request: Request = Request.Builder()
            .url(url!!)
            .get()
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                callback?.onFailure(e)
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                if (callback != null) {
                    if (response.isSuccessful) {
                        callback.onSuccess(if (response.body != null) response.body!!.string() else null)
                    } else {
                        callback.onError(response.code, response.message)
                    }
                }
            }
        })
    }

    /**
     * 定义回调接口
     */
    interface HttpCallback {
        fun onSuccess(response: String?) // 请求成功时返回响应内容
        fun onError(code: Int, message: String?) // 请求失败时返回错误码和错误信息
        fun onFailure(e: IOException?) // 请求异常时返回异常
    }
}